﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

/// <summary>
/// Use this class to define every responses to client
/// </summary>
public class AjaxResponse {
    string _message = "";
    /// <summary>
    /// Use this property to set response whether it's success or not
    /// </summary>
    /// <value>
    ///     0 : Error
    ///     1 : Success
    /// </value>
    public string Status { get; set; }
    /// <summary>
    /// Enter error message if Status property is set to 0, or enter success message if Status property is set to 1
    /// </summary>
    public string Message { get; set; }
    /// <summary>
    /// JSON formatted string
    /// </summary>
    public string Data { get; set; }
    /// <summary>
    /// If this property is set, page will be redirected to this url.
    /// </summary>
    public string RedirectUrl { get; set; }
    /// <summary>
    /// If this property is set, form tab will open based on gived form id, or focused if target form is already exist on tab list 
    /// & close current form automatically 
    /// </summary>
    public string RedirectFormId { get; set; }
    /// <summary>
    /// JSON formatted field names which raise errors
    /// [{"f":"fieldname","m":"error_message"}]
    /// </summary>
    public string ErrorFields { get; set; }

    public void SetStatus(FormValidation validation) {
        SetStatus(validation, "");
    }

    public void SetStatus(FormValidation validation, string successMessage) {
        if (validation.IsValid)
        {
            this.Status = "1";
            this.Message = successMessage;
        }
        else {
            this.Status = "0";
            this.ErrorFields = validation.GetErrorMessages(true);
        }
    }

    public string GenerateJSON() {
        string ef = string.IsNullOrEmpty(ErrorFields) || (ErrorFields == "[]") ? "" : ", \"error_fields\":" + ErrorFields + "";
        string dt = string.IsNullOrEmpty(Data) || (Data == "[]") ? "" : ", \"data\":" + Data + "";
        this.Message = !string.IsNullOrEmpty(this.Message) ? Regex.Replace(this.Message, @"\r\n?|\n", " ") : "";
        string js = "{\"status\":\"" + System.Security.SecurityElement.Escape(this.Status) + "\",\"message\":\"" + System.Security.SecurityElement.Escape(this.Message) + "\",\"redirect_url\":\"" + System.Security.SecurityElement.Escape(this.RedirectUrl) + "\",\"redirect_formid\":\"" + System.Security.SecurityElement.Escape(this.RedirectFormId) + "\"" + ef + dt + " }";
        return js;
    }
    
}
